import React, { useEffect, useState } from 'react';
import { View, Text } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { Avatar, Button } from '@nutui/nutui-react-taro';
import {
  ArrowRight,
  User,
  Bell,
  Shield,
  Service,
  Lock,
  Ask,
} from '@nutui/icons-react-taro';
import './index.scss';
import { BASE_URL } from '../../services/request';
import { useRoleStore, ROLE_TYPES } from '../../store/useRoleStore';
import { useInfoStore } from '../../store/useInfoStore';
import { taskApi } from '../../services/taskApi';
import { getCurrentTerm } from '../../utils/termDate';
import { useMemo } from 'react';

// 将菜单定义移到组件外部，避免在渲染中重新创建
const SETTINGS_MENU = [
  {
    id: 'profile',
    title: '个人资料',
    icon: <User color="#2196F3" />,
    iconBgColor: '#E3F2FD'
  },
  {
    id: 'notification',
    title: '通知设置',
    icon: <Bell color="#F44336" />,
    iconBgColor: '#FFEBEE'
  },
  {
    id: 'privacy',
    title: '隐私设置',
    icon: <Shield color="#9C27B0" />,
    iconBgColor: '#F3E5F5'
  }
];

const ABOUT_MENU = [
  {
    id: 'help',
    title: '帮助中心',
    icon: <Service color="#2196F3" />,
    iconBgColor: '#E3F2FD'
  },
  {
    id: 'policy',
    title: '隐私政策',
    icon: <Lock color="#757575" />,
    iconBgColor: '#F5F5F5'
  },
  {
    id: 'about',
    title: '关于我们',
    icon: <Ask color="#757575" />,
    iconBgColor: '#F5F5F5'
  }
];

const UserCenter = () => {
  const userInfo = useInfoStore(state => state.info);
  const currentRole = useRoleStore(state => state.userRole);
  const switchRole = useRoleStore(state => state.switchRole);
  const [averageScore, setAverageScore] = useState();

  const currentTerm = getCurrentTerm();


  useEffect(() => {
    const getAverageScore = async () => {
      const res = await taskApi.getAverageScore(
        {
          start_date: currentTerm.startDate,
          end_date: currentTerm.endDate,
        }
      );
      setAverageScore(res);
    };
    getAverageScore();
  }, []);

  // 简单的事件处理函数
  const handleMenuClick = (menuId) => {
    if (menuId === 'profile') {
      // 跳转到个人资料页面
      handleUserInfoClick();
    } else {
      Taro.showToast({
        title: '功能开发中',
        icon: 'none'
      });
    }
  };

  // 跳转到个人资料页面
  const handleUserInfoClick = () => {
    Taro.navigateTo({
      url: `/package-profile/pages/profile/index`
    });
  };

  // 角色切换
  const handleSwitchRole = () => {
    Taro.showModal({
      title: '切换身份',
      content: `确定要切换到${currentRole === ROLE_TYPES.LEADER ? '学生' : '组长'}端吗？`,
      success: (res) => {
        if (res.confirm) {
          switchRole(currentRole === ROLE_TYPES.LEADER ? ROLE_TYPES.STUDENT : ROLE_TYPES.LEADER);
          Taro.reLaunch({ url: '/pages/index/index' });
        }
      }
    });
  };

  // 退出登录
  const handleLogout = () => {
    Taro.showModal({
      title: '退出登录',
      content: '确定要退出当前账号吗？',
      success: (res) => {
        if (res.confirm) {
          // 清除token
          Taro.removeStorageSync('token');
          // 清除用户信息
          const setUserInfo = useInfoStore.getState().setInfo;
          const setDomain = useInfoStore.getState().setDomain;
          setUserInfo(null);
          setDomain(null);
          // 重置角色
          switchRole(ROLE_TYPES.STUDENT);
          // 跳转到登录页
          Taro.reLaunch({ url: '/package-login/pages/login/index' });
        }
      }
    });
  };

  const isUserLeader = userInfo?.role === 'leader' || userInfo?.role === 'subleader';
  const isUserAdmin =  userInfo?.role == 'admin' ;
  const userName = userInfo?.name || '未知';
  const userDepartment = userInfo?.department || '未知';
  const userId = userInfo?.id || '未知';
  const userAvatar = userInfo?.picture ? BASE_URL + userInfo.picture : '';

  const calculateAttitude = useMemo(() => {
    if (!averageScore)
      return '待评估';

    const avgScore = averageScore.average_score || 0;

    if (avgScore >= 95) {
      return '优';
    } else if (avgScore >= 85) {
      return '良';

    } else if (avgScore >= 75) {
      return '中';
    } else {
      return '差';
    };

  }, [averageScore]);


  return (
    <View className="user-center">
      {/* 用户资料卡片 */}
      <View className="user-card" onClick={handleUserInfoClick}>
        <View className="user-info">
          <View className="user-basic-info">
            <View className="avatar">
              <Avatar src={userAvatar} />
            </View>
            <View className="user-details">
              <Text className="user-name">{userName}</Text>
              <Text className="user-department">{isUserLeader ? '组长' : isUserAdmin ? '管理者' : '学生'} • {userDepartment}</Text>
              <Text className="user-id">学号: {userId}</Text>
            </View>
          </View>
          <View className="more-action">
            <ArrowRight color="#2f6eee" />
          </View>
        </View>

        {/* 用户统计数据 */}
        <View className="user-stats">
          <View className="stat-item">
            <Text className="stat-value">{averageScore?.yesterday_score || 0}</Text>
            <Text className="stat-label">昨日得分</Text>
          </View>
          <View className="stat-item">
            <Text className="stat-value">{averageScore?.average_score || 0}</Text>
            <Text className="stat-label">学期平均分</Text>
          </View>
          <View className="stat-item">
            <Text className="stat-value">{calculateAttitude}</Text>
            <Text className="stat-label">态度评估</Text>
          </View>
        </View>
      </View>

      {/* 账号与设置 */}
      <View className="section-title">
        <Text>账号与设置</Text>
      </View>
      <View className="menu-list">
        {SETTINGS_MENU.map(item => (
          <View
            key={item.id}
            className="menu-item"
            onClick={() => handleMenuClick(item.id)}
          >
            <View className="menu-icon" style={{ backgroundColor: item.iconBgColor }}>
              {item.icon}
            </View>
            <Text className="menu-title">{item.title}</Text>
            <View className="menu-arrow">
              <ArrowRight color="#CCCCCC" />
            </View>
          </View>
        ))}
      </View>

      {/* 关于与帮助 */}
      <View className="section-title">
        <Text>关于与帮助</Text>
      </View>
      <View className="menu-list">
        {ABOUT_MENU.map(item => (
          <View
            key={item.id}
            className="menu-item"
            onClick={() => handleMenuClick(item.id)}
          >
            <View className="menu-icon" style={{ backgroundColor: item.iconBgColor }}>
              {item.icon}
            </View>
            <Text className="menu-title">{item.title}</Text>
            <View className="menu-arrow">
              <ArrowRight color="#CCCCCC" />
            </View>
          </View>
        ))}
      </View>

      {/* 功能按钮区域 */}
      <View className="action-buttons">
        {isUserLeader || isUserAdmin ? (
          <Button
            className="action-button switch-role-button"
            onClick={handleSwitchRole}
          >
            切换为{currentRole === ROLE_TYPES.LEADER ? '学生' : '组长'}端
          </Button>
        ) : currentRole === ROLE_TYPES.LEADER && (
          <Button
            className="action-button switch-role-button"
            onClick={handleSwitchRole}
          >
            回到学生端
          </Button>
        )}

        <Button
          className="action-button logout-button"
          onClick={handleLogout}
        >
          退出登录
        </Button>
      </View>
    </View>
  );
};

export default UserCenter;